package com.ddyang.Webflux.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioUtil {
    /**
     * 写消息
     *
     * @param client
     * @param message
     * @return
     * @throws IOException
     */
    public static ByteBuffer writeMessage(SocketChannel client, String message) throws IOException {
        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);

        writeBuffer.put(message.getBytes());
        writeBuffer.flip();
        client.write(writeBuffer);
        return writeBuffer;
    }

    /**
     * 读取消息
     *
     * @throws IOException
     */
    public static String readMessage(SocketChannel socketChannel) throws IOException {

        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        int count = socketChannel.read(readBuffer);

        String receivedMessage = null;
        if (count > 0) {
            receivedMessage = new String(readBuffer.array(), 0, count);
            System.out.println("收到消息:" + receivedMessage);
        }
        return receivedMessage;
    }

    static SocketChannel acceptClient(Selector selector, SelectionKey selectionKey) throws IOException {
        SocketChannel client;
        ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
        client = server.accept();
        client.configureBlocking(false);
        client.register(selector, SelectionKey.OP_READ);
        return client;
    }
}
